package com.example.demo.util;

import com.example.demo.model.entity.Student;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

public class ExcelExportUtil {

    /**
     * 导出学生信息为Excel
     * @param students 学生列表
     * @return 字节数组（Excel文件流）
     */
    public static byte[] exportStudentsToExcel(List<Student> students) throws IOException {
        // 创建工作簿
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("相似学生信息");

            // 创建表头
            String[] headers = {"排名", "姓名", "平均学分绩点", "英语四级成绩",
                    "高等数学（上）", "高等数学（下）",
                    "大学英语1", "大学英语2", "大学英语3", "大学英语4",
                    "录取院校", "专业"};
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                // 设置表头样式（可选）
                CellStyle style = workbook.createCellStyle();
                Font font = workbook.createFont();
                font.setBold(true);
                style.setFont(font);
                cell.setCellStyle(style);
            }

            // 填充数据
            for (int i = 0; i < students.size(); i++) {
                Student student = students.get(i);
                Row row = sheet.createRow(i + 1);
                row.createCell(0).setCellValue(i + 1); // 使用索引作为排名
                row.createCell(1).setCellValue("学生" + student.getId()); // 使用ID作为姓名
                row.createCell(2).setCellValue(student.getGpa());
                row.createCell(3).setCellValue(student.getCet4());
                row.createCell(4).setCellValue(student.getMath1());
                row.createCell(5).setCellValue(student.getMath2());
                row.createCell(6).setCellValue(student.getEnglish1());
                row.createCell(7).setCellValue(student.getEnglish2());
                row.createCell(8).setCellValue(student.getEnglish3());
                row.createCell(9).setCellValue(student.getEnglish4());
                row.createCell(10).setCellValue(student.getSavedTargetSchool()); // 使用savedTargetSchool
                row.createCell(11).setCellValue(student.getSavedMajor()); // 使用savedMajor
            }

            // 自适应列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }

            // 转换为字节数组
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            return outputStream.toByteArray();
        }
    }
}
